package first.endtoend;


import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

/**
 * Created with IntelliJ IDEA.
 * User: Olfa
 * Date: 18/09/13
 * Time: 17:02
 * To change this template use File | Settings | File Templates.
 */
public class EncryptDecrypt
{
    public static final String DES_ENCRYPTION_SCHEME = "DES";
    private static final String UNICODE_FORMAT = "UTF8";
    private final String myEncryptionKey = "MGMCAQACEQDj/0UOgifcgm9/i0gK8mpvAgMBAAECEFGh727PaUhI+mIFpVADW6kCCQD4lLnFoBoNMwIJAOrNRi/SjtXVAghrd3jc/HtmywIJALtc4kz28BOhAgkArjx2GPNU2/c=" +
            "x3rMS4G9V2pZVsITEpZ5MYtQnm5nr2e0KOPOw+WFXS4=";
    byte[] arrayBytes;
    private KeySpec ks;
    private SecretKeyFactory skf;
    private Cipher cipher;
    private SecretKey key;

    public void initializeKey() throws Exception
    {
        arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
        ks = new DESKeySpec(arrayBytes);
        skf = SecretKeyFactory.getInstance(DES_ENCRYPTION_SCHEME);
        key = skf.generateSecret(ks);

    }

    /**
     * @param unencryptedString
     * @return
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidKeySpecException
     */
    public String encrypt(String unencryptedString) throws InvalidKeyException,
            NoSuchAlgorithmException, NoSuchPaddingException,
            InvalidKeySpecException
    {
        System.out.println("****** in encrypt method" + unencryptedString);
        String encryptedString = "";
        try
        {

            initializeKey();
            arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
            cipher = Cipher.getInstance(DES_ENCRYPTION_SCHEME);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
            byte[] encryptedText = cipher.doFinal(plainText);
            encryptedString = new String(Base64.encodeBase64(encryptedText));

        } catch (Exception e)
        {
            e.printStackTrace();
        }

        return encryptedString;
    }

    /**
     * @param message
     * @return
     * @throws Exception
     */
    public String decrypt(byte[] message) throws Exception
    {
        initializeKey();
        final Cipher decipher = Cipher.getInstance(DES_ENCRYPTION_SCHEME);
        decipher.init(Cipher.DECRYPT_MODE, key);
        final byte[] plainText = decipher.doFinal(message);
        return new String(plainText, "UTF-8");
    }


}
